package com.island.practice.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.island.practice.entity.Role;
import com.island.practice.entity.PersonRoleRelation;

public class MaintainRoleServlet extends AbstractServlet{
	
	private static final String SQL_QUERY_ROLE = "SELECT * FROM ROLE WHERE ROLE_ID = ?";
	private static final String SQL_UPDATE_ROLE = "UPDATE ROLE SET ROLE_NAME = ? WHERE ROLE_ID = ?";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String roleId = request.getParameter("roleId");
		PreparedStatement statement = null;
		Connection connection = null;
		ResultSet resultset = null;
		Role role = null;
		
		try{
			connection = this.getConnection();
			statement = connection.prepareStatement(SQL_QUERY_ROLE);
			statement.setString(1, roleId);
			resultset = statement.executeQuery();
			
			if(resultset.next())
			{
				role = new Role();
				role.setRoleId(resultset.getString("ROLE_ID"));
				role.setRoleName(resultset.getString("ROLE_NAME"));
			}

		}catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("Maintain role(roleId:" + roleId + ")", e);
		} finally {
			closeStatement(statement);
			closeConnection(connection);
		}
		request.setAttribute("role", role);
		//forward the result to a new MaintainRole
    	request.getRequestDispatcher("/Role/MaintainRole.jsp").forward(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		PreparedStatement statement = null;
		Connection connection = null;
		String roleId = request.getParameter("roleId");
		String roleName = request.getParameter("roleName");
		
		try
		{
			connection = this.getConnection();
			connection.setAutoCommit(false);
			statement = connection.prepareStatement(SQL_UPDATE_ROLE);
			statement.setString(1, roleName);
			statement.setString(2, roleId);
			statement.execute();
			connection.commit();
			
		} catch (SQLException e)
		{	
			try {
            connection.rollback();
			} catch (SQLException e1) {
            e1.printStackTrace();
			}			
			e.printStackTrace();
			throw new RuntimeException("Maintain role(roleId:" + roleId + ") failed", e);
		} finally
		{
			closeStatement(statement);
			closeConnection(connection);
		}
		
		request.getRequestDispatcher("ListRole").forward(request, response);
				
	}
	
}
